﻿using System.Collections.Generic;
using System.Linq;

using SIG.Model;
using SIG.Repository;

using SIG.Infrastructure.Logging;
using SIG.Infrastructure.Cache;
using SIG.Infrastructure.Configs;
using SIG.Resources;
using System.Linq.Expressions;
using System;
using SIG.Basic.Extensions;
using SIG.Model.Emails;
using SIG.Resources.Admin;
using System.Net.Mail;
using SIG.Infrastructure.Helper;
using System.Net;

namespace SIG.Service
{
    public class EmailService: EntityService<Email>, IEmailService
    {
     
        private readonly IEmailRepository _emailRepository;
        private readonly ILoggingService _loggingService;
        private readonly ICacheService _cacheService;

        public EmailService(IEmailRepository emailRepository, ILoggingService loggingService, ICacheService cacheService)
            : base(emailRepository, cacheService, loggingService)
        {
           
            _emailRepository = emailRepository;
            _loggingService = loggingService;
            _cacheService = cacheService;
        }

        public IEnumerable<Email> GetActiveEmails()
        {
            //get list
            var key = $"{EntityNames.Email}_ActiveList";

            List<Email> emails;
            if (SettingsManager.Email.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    emails = (List<Email>)_cacheService.Get(key);

                }
                else
                {
                    emails = _emailRepository.GetFilteredElements(c=>c.Active).ToList();
                    _cacheService.Set(key, emails, SettingsManager.Email.CacheDuration);
                }
            }
            else
            {
                emails = _emailRepository.GetFilteredElements(c => c.Active).ToList();
            }

            return emails;
        }


        public List<Email> GetPagedElements(int pageIndex, int pageSize, string keyword, bool active, out int totalCount)
        {

            //get list count
            var keyCount = $"{EntityNames.Email}_ListCount_{keyword}_{active}";

            var totalIQuery = _emailRepository.GetAllElements().Where(m=>m.Active== active);
            if (!string.IsNullOrEmpty(keyword))
                totalIQuery = totalIQuery.Where(g => g.Subject.Contains(keyword));
         

            if (SettingsManager.Email.EnableCaching)
            {
                if (_cacheService.IsSet(keyCount))
                {
                    totalCount = (int)_cacheService.Get(keyCount);
                }
                else
                {
                    totalCount = totalIQuery.Count();
                    _cacheService.Set(keyCount, totalCount, SettingsManager.Email.CacheDuration);
                }
            }
            else
            {
                totalCount = totalIQuery.Count();
            }


            //get list
            var key = $"{EntityNames.Email}_List_{pageIndex}_{pageSize}_{keyword}_{active}";

            List<Email> email;
            Expression<Func<Email, bool>> filter = g => g.Active == active;
            Expression<Func<Email, bool>> filterByKeyword = g => g.Subject.Contains(keyword);
         

            if (!string.IsNullOrEmpty(keyword))
                filter = filter.AndAlso(filterByKeyword);
           


            if (SettingsManager.Email.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    email = (List<Email>)_cacheService.Get(key);

                }
                else
                {
                    email = _emailRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false).ToList();
                    _cacheService.Set(key, email, SettingsManager.Email.CacheDuration);
                }
            }
            else
            {
                email = _emailRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false).ToList();
            }

            return email;

        }

        public IEnumerable<Email> LatesterEmails(int count)
        {
            var key = $"{EntityNames.Email}s_Latester_{count}";

            if (!SettingsManager.Email.EnableCaching)
            {
                return _emailRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Email>)_cacheService.Get(key);

            }

            var emailList = _emailRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            _cacheService.Set(key, emailList, SettingsManager.Email.CacheDuration);


            return emailList;
        }

        public bool DeleteEmails(int[] Ids)
        {
           
            // string[] ids = Ids.Split(',');
            //long[] IdItems = Array.ConvertAll<string, long>(ids, long.Parse);  
            //List<Email> lEmails = _uow.Emails.GetAll().Where(e=>IdItems.Contains(e.Id)).ToList();
            try
            {
                foreach (int id in Ids)
                {
                    Email vEmail = _emailRepository.GetElementById(id);
                    if (vEmail != null)
                    {
                        vEmail.Active = false;
                      //  _emailRepository.Attach(vEmail);
                        _emailRepository.SetModified(vEmail);

                    }
                }
                _emailRepository.UnitOfWork.Commit();
                _cacheService.Invalidate(EntityNames.Email);

                _loggingService.Info(string.Format(Logs.BulkTrash, EntityNames.Email));
            }
            catch (Exception er)
            {
                _loggingService.Error(er.Message, er);
                return false;
            }

            return true;
        }
        /// <summary>
        /// 彻底删除
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public bool RemoveEmails(int[] Ids)
        {          

            try
            {
                foreach (int id in Ids)
                {
                    Email vEmail = _emailRepository.GetElementById(id);
                    if (vEmail != null)
                    {
                        _emailRepository.Remove(vEmail);                      
                    }
                }
                _emailRepository.UnitOfWork.Commit();
                _cacheService.Invalidate(EntityNames.Email);
                _loggingService.Info(string.Format(Logs.BulkRemove, EntityNames.Email));
            }
            catch (Exception er)
            {
                _loggingService.Error(er.Message, er);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 还原邮件
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public bool RestoreEmails(int[] Ids)
        {

            try
            {
                foreach (int id in Ids)
                {
                    Email vEmail = _emailRepository.GetElementById(id);
                    if (vEmail != null)
                    {
                        vEmail.Active = true;                      
                        _emailRepository.SetModified(vEmail);
                    }
                }
                _emailRepository.UnitOfWork.Commit();
                _cacheService.Invalidate(EntityNames.Email);

                _loggingService.Info(string.Format(Logs.BulkTrash, EntityNames.Email));
            }
            catch (Exception er)
            {
                _loggingService.Error(er.Message, er);
                return false;
            }

            return true;
        }

        ///// <summary>
        ///// 发送邮件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="email"></param>
        ///// <param name="subject"></param>
        ///// <param name="body"></param>
        //public bool SendMail(string sender, string email, string subject, string body)
        //{
        //    try
        //    {
        //        MailMessage message = new MailMessage();

        //        var mailto = SettingsManager.Contact.MailTo;
        //      //  var mailcc = SettingsManager.Contact.MailCC;

        //        message.To.Add(email);

        //        //if (!string.IsNullOrEmpty(mailcc))
        //        //    message.CC.Add(mailcc);

        //        message.Subject = subject;
        //        message.Body = body; //string.Format("<p>{0}</p><p>发件人：{1} ({2}), 发件人邮箱：{3}</p>", body, name, phone, from);
        //        message.IsBodyHtml = true;

        //        message.ReplyToList.Add(new MailAddress(mailto, sender));


        //        var cipherText = SettingsManager.SMTP.Password;
        //        var pwd = EncryptionHelper.Decrypt(cipherText);

        //        message.From = new MailAddress(SettingsManager.SMTP.From, sender);


        //        SmtpClient smtpClient = new SmtpClient(SettingsManager.SMTP.SmtpServer, SettingsManager.SMTP.Port);

        //        smtpClient.UseDefaultCredentials = true;
        //        smtpClient.EnableSsl = SettingsManager.SMTP.EnableSsl;
        //        //   smtpClient.Port = SettingsManager.SMTP.Port;
        //        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        //        smtpClient.Credentials = new NetworkCredential(SettingsManager.SMTP.UserName, pwd);

        //        smtpClient.Send(message);

        //        _loggingService.Info(string.Format(Logs.ReplyEmail, Site.CurrentUserName, subject));
        //        return true;
        //    }
        //    catch (Exception er)
        //    {
        //        _loggingService.Error(er.Message, er);
               
        //        return false;
        //    }
        //}


    }
}
